package main

import (
	"fmt"
	"git.phjr.com/devops/pkg/config"
	"git.phjr.com/devops/pkg/ssh"
	"github.com/spf13/viper"
)

func main() {
	config.Init("config")
	gitUrl := viper.GetString("git.gitUrl")

	/**
	创建ssh client
	*/
	publisher, _ := ssh.NewClient(viper.GetString("publisher.host"), viper.GetString("publisher.port"), viper.GetString("publisher.user"), viper.GetString("publisher.password")).CreateClient()
	ssh1, _ := ssh.NewClient(viper.GetString("ssh1.host"), viper.GetString("ssh1.port"), viper.GetString("ssh1.user"), viper.GetString("ssh1.password")).CreateClient()
	/**
	通过client创建ssh session
	*/
	publisherSsh, _ := publisher.CreatesshSession()
	ssh1Ssh, _ := ssh1.CreatesshSession()
	/**
	通过client创建sftp session
	*/
	publisherSftp, _ := publisherSsh.CreatesftpSession()
	ssh1Sftp, _ := ssh1Ssh.CreatesftpSession()
	/**
	 * 第一步：拉取代码，编译代码
	 */
	var buildCmds []string
	buildCmds = append(buildCmds, "cd /mnt")
	buildCmds = append(buildCmds, "echo \"删除原有代码\"")
	buildCmds = append(buildCmds, "rm -rf /mnt/qiqi-study")
	buildCmds = append(buildCmds, "echo \"拉取git代码\"")
	buildCmds = append(buildCmds, "git clone "+gitUrl)
	buildCmds = append(buildCmds, "cd /mnt/qiqi-study")
	buildCmds = append(buildCmds, "echo \"打包代码\"")
	buildCmds = append(buildCmds, "mvn package")
	publisherSsh.Shell(buildCmds)
	/**
	 * 第二步：下载编译好的jar文件到本地
	 */
	fmt.Println("开始下载ing")
	publisherSftp.Download("/mnt/qiqi-study/target/study-java-0.0.1-SNAPSHOT.jar", "./backup")
	fmt.Println("开始下载完成")
	/**
	 * 第三步：上传jar文件到部署服务器
	 */
	fmt.Println("开始上传ing")
	ssh1Sftp.Upload("./backup/study-java-0.0.1-SNAPSHOT.jar", "/mnt/data/study")
	fmt.Println("开始上传完成")
	/**
	 * 第四步：重启容器
	 */
	fmt.Println("重启容器")
	var startCmds []string
	startCmds = append(startCmds, "docker restart study")
	startCmds = append(startCmds, "docker logs -f study")
	ssh1Ssh.Shell(startCmds)
	fmt.Println("完成")
}
